var React = require('react');

var Header = require('../widget/Header');
var Bheader = require('../widget/Bheader');
var Footer = require('../widget/Footer');
var MsgBox = require('../components/MsgBox');
var ShopPro = require('../components/ShopPro');
var IncreaseId = require('../../web/tools/IncreaseId');
var ajax = require('../tools/ajax');
var Icon = require('../components/Icon');
var AttrContent = require('../widget/AttrContent');

module.exports = React.createClass({
    getInitialState: function () {
        this.pullDownTips = {
            // 下拉状态
            0: '下拉发起刷新',
            1: '继续下拉刷新',
            2: '松手即可刷新',
            3: '正在刷新',
            4: '刷新成功'
        };
        this.pullUpTips = {
            // 上拉状态
            0: '上拉发起加载',
            1: '松手即可加载',
            2: '正在加载',
            3: '加载成功'
        };
        this.itemsChanged = false;
        return {
            theme:"Default", //Default/Blue
            limit:0,
            items:[],
            oldItems:[],
            pullUpStatus:0,
            pullDownStatus: 3,
            isTouching:false,
            flag:true,
            goods_id:"",
            hact:"#",//地址
            classify:"",//店铺分类
            names:[],//分类名称
            catagory_id:"",
            pullUpFlag:false
        }
    },
    myScroll:"",
    componentDidMount: function () {
        this.getCatagoryName();
        this.getGoodsInfoByCateid(0,"");
        setTimeout(this.iscroll,500);
    },
    componentDidUpdate() {
        var p=this;
        // 仅当列表发生了变更，才调用iscroll的refresh重新计算滚动条信息
        if (this.itemsChanged) {
            setTimeout(function () {
                p.myScroll.refresh();
            }, 0);
        }
    },
    /**iScroll插件*/
    iscroll(){
        var p =this;
        var options = {
            // 默认iscroll会拦截元素的默认事件处理函数，我们需要响应onClick，因此要配置
            preventDefault: false,
            // 禁止缩放
            zoom: false,
            // 支持鼠标事件，因为我开发是PC鼠标模拟的
            mouseWheel: true,
            // 滚动事件的探测灵敏度，1-3，越高越灵敏，兼容性越好，性能越差
            probeType: 3,
            // 拖拽超过上下界后出现弹射动画效果，用于实现下拉/上拉刷新
            bounce: true,
            // 展示滚动条
            scrollbars: false
        };
        p.myScroll = new IScroll("#ScrollContainer",options);
        p.myScroll.on("scroll", p.onScroll);
        p.myScroll.on("scrollEnd", p.onScrollEnd);
    },
    onScroll() {
        // 下拉区域
        if (this.myScroll.y <= this.myScroll.maxScrollY + 5) {
            this.onPullUp();
        }
    },
    onScrollEnd() {
        var p=this;
        // 滑动结束后，停在加载区域
        if (p.myScroll.y <= p.myScroll.maxScrollY) {
            // 发起了加载，那么更新状态
            var limit = p.state.limit;
            var catagory_id = p.state.catagory_id;
            limit = limit + 6;
            p.setState({limit:limit,pullUpFlag:true},()=>{
                p.itemsChanged = true;
                setTimeout(function(){
                    p.getGoodsInfoByCateid(limit,catagory_id);
                },1500);
            });
        }
    },
    onTouchStart() {
        this.setState({isTouching:true});
    },
    onTouchEnd() {
        this.setState({isTouching:false});
    },
    onPullDown() {
        // 手势
        if (this.state.isTouching) {
            if (this.myScroll.y > 5) {
                this.state.pullDownStatus != 2 && this.setState({pullDownStatus: 2});
            } else {
                this.state.pullDownStatus != 1 && this.setState({pullDownStatus: 1});
            }
        }
    },
    onPullUp() {
        // 手势
        if (this.state.isTouching) {
            if (this.myScroll.y <= this.iScrollInstance.maxScrollY - 5) {
                this.state.pullUpStatus != 1 && this.setState({pullUpStatus: 1});
            } else {
                this.state.pullUpStatus != 0 && this.setState({pullUpStatus: 0});
            }
        }
    },
    /**店铺分类名称*/
    getCatagoryName(){
        var p=this;
        var shop_id = localStorage.getItem("shopId");
        ajax("POST","getCatagoryName",{shop_id:shop_id},function(dt){
            if(dt && dt.success) {
                var names = dt.data;
                p.setState({names:names});
            }
        })
    },
    /**获取店铺分类下的商品*/
    getGoodsInfoByCateid(limit,catagory_id){
        var p =this;
        p.setState({pullUpFlag:false});
        if(limit !=0){
            limit = p.state.limit;
        }
        var shop_id = localStorage.getItem("shopId");
        ajax("POST","getShopProinfo",{shop_id:shop_id,limit:limit,catagory_id:catagory_id},function(dt){
            if(dt.data.length > 0 && dt.success){
                var objs = dt.data;
                console.log(objs);
                var items = p.state.items;
                var oldItems = p.state.oldItems;
                if(oldItems.length>0){
                    if(objs[0].id !== oldItems[0].id){
                        for(var i=0;i<objs.length;i++){
                            items.push(objs[i]);
                        }
                    }
                }else{
                    items = objs;
                }
                p.setState({items:items,oldItems:objs});
                if(p.myScroll){
                    p.myScroll.refresh();
                }
            }else{
                p.refs.MsgBox.setState({
                    type: "no",
                    timeout:750,
                    show:true,
                    word:"已经到底了"
                })
            }
        });
    },
    /**点击分类*/
    cate(e){
        var p=this;
        var limit = 0;
        var catagory_id = e.currentTarget.getAttribute("data");
        this.setState({items:[],oldItems:[],catagory_id:catagory_id},()=>{
            p.getGoodsInfoByCateid(limit,catagory_id);
        });

    },
    /**商品详情*/
    action: function (e){
        var action = e.currentTarget.getAttribute("action");
        var id = e.currentTarget.getAttribute("data-id");
        var price = e.currentTarget.getAttribute("data-price");
        localStorage.setItem("back","#shop_pro");
        localStorage.setItem("goods_id",id);
        localStorage.setItem("price",price);
        location.href = action;
    },
    render: function () {
        var p = this;
        var names = p.state.names;
        var shop_scorllimage = localStorage.getItem("shop_scorllimage");
        if(names[0]){
            var nameList = names.map(function(obj){
                return(
                    <li key={obj.Id} className={p.state.catagory_id == obj.Id ?"ac":""}  onClick={p.cate} data={obj.Id}>{obj.catagory_name}</li>
                )
            });
        }
        var objs = p.state.items;
        var odd = [];
        var even = [];
        for(var i = 0;i <objs.length;i++){
            if(i%2 == 0){
                odd.push(objs[i]);
            }else{
                even.push(objs[i]);
            }
        }
        var shoplist_l = odd.map(function(obj,index){
            if(obj.goods_img) {
                var goods_img = obj.goods_img.split(",")[0];
            }
            return(
                <div key={index} className="box" onClick={p.action} action="#goodDetail" data-id={obj.id} data-shop-id={obj.shop_id} data-name={obj.goods_name} data-number={obj.goods_number} data-price={obj.ProPrice}>
                    <div className="pic">
                        <img src={goods_img} />
                    </div>
                    <div className="shop_pro">
                        <p className="pname" ref="goodname">{obj.goods_name}</p>
                        <p className="p_des">{obj.goods_desc}</p>
                        <span className="p_des" ref="goodnumber">{obj.goods_number}</span><span className="p_des">件</span>
                    </div>
                    <div className="spro_con">
                        <div className="pro_country">

                        </div>
                        <div className="pro_price">
                            <span ref="goodprice">{obj.ProPrice}</span><span>元</span>
                        </div>
                        <div className="pro_addcart">
                            <Icon icon="#icon-gouwuche-tianjia"></Icon>
                        </div>
                    </div>
                </div>
            )
        });
        var shoplist_r = even.map(function(obj,index){
            if(obj.goods_img) {
                var goods_img = obj.goods_img.split(",")[0];
            }
            return(
                <div key={index} className="box" onClick={p.action} action="#goodDetail" data-id={obj.id} data-shop-id={obj.shop_id} data-name={obj.goods_name} data-number={obj.goods_number} data-price={obj.ProPrice}>
                    <div className="pic">
                        <img src={goods_img} />
                    </div>
                    <div className="shop_pro">
                        <p className="pname" ref="goodname">{obj.goods_name}</p>
                        <p className="p_des">{obj.goods_desc}</p>
                        <span className="p_des" ref="goodnumber">{obj.goods_number}</span><span className="p_des">件</span>
                    </div>
                    <div className="spro_con">
                        <div className="pro_country">

                        </div>
                        <div className="pro_price">
                            <span ref="goodprice">{obj.ProPrice}</span><span>元</span>
                        </div>
                        <div className="pro_addcart">
                            <Icon icon="#icon-gouwuche-tianjia"></Icon>
                        </div>
                    </div>
                </div>
            )
        });
        return (
            <div className="main"  id="main">
                <Bheader  ref="bheader" theme={p.state.theme} title="店铺商品" hact="#"></Bheader>
                <div id="ScrollContainer" onTouchStart={this.onTouchStart} onTouchEnd={this.onTouchEnd} onScroll={this.handleScroll}>
                    <div className="shopProWrap">
                        <div id="fenClassPro">
                            <div id="fenClassProImg"><img src={shop_scorllimage} /></div>
                            <ul className="fenClassNum">
                                <li className={p.state.catagory_id == "" ?"ac":""} onClick={p.cate} data="">全部</li>
                                {nameList}
                            </ul>
                        </div>
                        <p className="blankSet"></p>
                        <div className="pro">
                            <div className="pro-left">
                                {shoplist_l}
                            </div>
                            <div className="pro-right">
                                {shoplist_r}
                            </div>
                        </div>
                        <div className="pullUp" style={{visibility:p.state.pullUpFlag?"visible":"hidden"}}>
                            <div className="refresh loading"></div>
                        </div>
                    </div>
                </div>
                <MsgBox ref="MsgBox"></MsgBox>
            </div>
        )
    }
});
